package com.source.diyjuc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @Author wengqy
 * @Date 2021/1/18
 */
public class ABADemo4 {

    static AtomicStampedReference<Integer> atomicStampedReference  = new AtomicStampedReference<>(100,1);

    public static void main(String[] args) {

        new Thread(()->{

            int stamp = atomicStampedReference.getStamp();
            // 获得版本号
            System.out.println("T1 stamp =>" + stamp);

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("11   "+atomicStampedReference.getReference() +"  "+atomicStampedReference.getStamp()+"  "+Thread.currentThread().getName());

            boolean t1 = atomicStampedReference.compareAndSet(100, 200, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
            System.out.println("t1  "+t1);
            System.out.println("22   "+atomicStampedReference.getReference() +"  "+atomicStampedReference.getStamp()+"  "+Thread.currentThread().getName());

            boolean t12 = atomicStampedReference.compareAndSet(200, 100, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
            System.out.println("t12  "+t12);
            System.out.println("33   "+atomicStampedReference.getReference() +"  "+atomicStampedReference.getStamp()+"  "+Thread.currentThread().getName());


        },"T1").start();



      new Thread(()->{

            int stamp = atomicStampedReference.getStamp();
            // 获得版本号
            System.out.println("T2 stamp =>" + stamp);
            try {
                TimeUnit.SECONDS.sleep(4);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("44   "+atomicStampedReference.getReference() +"  "+atomicStampedReference.getStamp()+"  "+Thread.currentThread().getName());

            boolean b = atomicStampedReference.compareAndSet(100, 999, stamp, stamp + 1);
            System.out.println(b);
            System.out.println("55   "+atomicStampedReference.getReference() +"  "+atomicStampedReference.getStamp()+"  "+Thread.currentThread().getName());

        },"T2").start();


    }
}
